#!/bin/python

##########################################################
# PROJECT   : GPRS Server
# FILE      : mainCall.py
# USAGE		: read cmd from 'msg',read one delete one 
# CREATION  : 200100829
# LICENSE   : ISCAS
# $Id$      : Qi Chen
# last time changed: 20101011
##########################################################
import time 
import random
import threading
import signal,os
import traceback
import binascii

from socketServer2 import server
from socketServer2 import receive
from socketServer2 import insert
from socketServer2 import send
from SerialRW import ReadSinkData
from SerialRW import SerialRW
#from DataConverts import GPRSToAM
#from DataConverts import AMToGPRS

'''
global viriable
'''
port = 8001
exitFlag = False


'''
set Ctrl-C handler
@param :connection,address
@return :
'''
def handler(signum, frame):
    exitFlag = True
    s.stop() 
    print 'Signal handler called with Ctrl-C'
   
    os._exit(1)

def controlFlow():
    while not exitFlag:
        data = ReadSinkData()
        if data != '':
            try:
                send(data)
            except Exception, error:
                traceback.print_exc()
            
        cmd=''
        try:
            cmd = receive()
        except Exception, error:
            #print '[!!Error in mainCall:]',error
            traceback.print_exc()
            
        if cmd != '':
            try:
                srw.SinkSerialWriter(cmd)
            except Exception,  msg:
                traceback.print_exc()
        
if __name__=='__main__':
    signal.signal(signal.SIGINT,handler)
    '''
    Gateway initiation
    open SerialRW,tcp server
    '''
    print '\n---------------mainCall init--------------'
    try:
      s = server()
      srw = SerialRW()
      srw.start()
    except Exception, error:
      pass
    threading.Thread(controlFlow())

